package com.mccraywebtech.controller;

import java.util.ArrayList;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.mccraywebtech.models.Contact;
import com.mccraywebtech.services.GenericService;


@Controller("contactController")
public class ContactController {
	@Autowired
	@Qualifier("contactService")
	private GenericService<Contact> contactService;

	/**
	 * @return the contactService
	 */
	public GenericService<Contact> getContactService() {
		return contactService;
	}

	/**
	 * @param contactService the contactService to set
	 */
	public void setContactService(GenericService<Contact> contactService) {
		this.contactService = contactService;
	}

	@RequestMapping("/index")
	public String listContacts(Map<String, Object> map) {
		System.out.println("In controller...");
		map.put("contact", new Contact());
		map.put("contactList", (ArrayList<Contact>)contactService.getAllObjects());

		return "contacts";
	}

	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public String addContact(@ModelAttribute("contact") Contact contact,
			BindingResult result) {

		contactService.saveObject(contact);

		return "redirect:/index";
	}

	@RequestMapping("/delete/{contactId}")
	public String deleteContact(@PathVariable("contactId") Integer contactId) {

		contactService.deleteObject(contactId);
		return "redirect:/index";
	}
	
	@RequestMapping("/update/{contactId}")
	public String getUpdateContact(@PathVariable("contactId") Integer contactId,
			Map<String, Object> map) {
		Contact c = (Contact) contactService.getObject(contactId);
		map.put("contact", c);
		return "update";
	}
	
	@RequestMapping("/update/performUpdate")
	public String updateContact(@ModelAttribute("contact") Contact contact,
			BindingResult result) {
		Contact c = (Contact) contactService.getObject(contact.getId());
		c.setEmail(contact.getEmail());
		c.setFirstName(contact.getFirstName());
		c.setLastName(contact.getLastName());
		c.setPhone(contact.getPhone());
		
		contactService.updateObject(c);
		return "redirect:/index";
	}
}
